function XOOS = PLS(XBase,MktmRf,T1,T2,T3)

% Only for 1 period ahead prediction
% variables are not passed lead/lagged. If a variable or return is passed
% as X(t), it means that it was known at time 't' (not t+1, not t-1)

% T1 is sample begin date, T3 is sample end date, and T2 is date from which
% the first oos forecast begins

% There is one XOOS variable for each vintage. Example, XOOS(:,t) will be
% the XOSS variable constructed at time 't' using information available
% only upto time t

[T,K] = size(XBase);
XOOS = NaN(T,T);
for t = T2:T3
    Predictor = XBase;
    s = std(Predictor(T1:t,:),'omitnan');
    Predictor(T1:t,:) = Predictor(T1:t,:)./repmat(s,t-T1+1,1); %standadrize
    % 1st stage
    phi = NaN(K,1);
    X = MktmRf(T1+1:t); %next peiod return
    for n = 1:K
        Y = Predictor(T1:t-1,n); % lagged X's
        idx = isfinite(Y) & isfinite(X);
        bb = [ones(sum(idx),1) X(idx)]\Y(idx);
        phi(n) = bb(2);
    end
    % 2nd stage
    Fac = NaN(T,1);
    X = phi;
    for s = T1:t
        Y = Predictor(s,:)';
        idx = isfinite(Y) & isfinite(X);
        bb = [ones(sum(idx),1) X(idx)]\Y(idx);
        Fac(s) = bb(2);
    end
    XOOS(:,t) = Fac;
end
return